/**
 * 
 */
package com.hanhai.zrb.api.facade.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.jws.WebService;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageInfo;
import com.hanhai.zrb.api.biz.service.CityInfoService;
import com.hanhai.zrb.api.biz.service.CommonCounterService;
import com.hanhai.zrb.api.biz.service.FundService;
import com.hanhai.zrb.api.biz.service.IndustryService;
import com.hanhai.zrb.api.biz.service.ProjectService;
import com.hanhai.zrb.api.biz.service.ResourceMatchService;
import com.hanhai.zrb.api.biz.service.SysDictionaryService;
import com.hanhai.zrb.api.biz.util.DateUtil;
import com.hanhai.zrb.api.client.facade.FundFacade;
import com.hanhai.zrb.api.client.facade.ResourceMatchFacade;
import com.hanhai.zrb.model.common.CommonCounterKey;
import com.hanhai.zrb.model.common.SysDictionary;
import com.hanhai.zrb.model.common.enums.ProvinceEnum;
import com.hanhai.zrb.model.common.enums.StatusEnums;
import com.hanhai.zrb.model.fund.Fund;
import com.hanhai.zrb.model.fund.dto.FundDto;
import com.hanhai.zrb.model.fund.vo.AppFundDetailVo;
import com.hanhai.zrb.model.fund.vo.AppFundVo;
import com.hanhai.zrb.model.fund.vo.FundSearchVo;
import com.hanhai.zrb.model.intention.Intention;
import com.hanhai.zrb.model.project.CityInfo;
import com.hanhai.zrb.model.project.Industry;
import com.hanhai.zrb.model.project.Project;
import com.hanhai.zrb.model.resourcematch.ResourceMatchContent;
import com.hanhai.zrb.model.resourcematch.ResourceMatchResult;
import com.hanhai.zrb.model.resourcematch.ResourceMatchTypeEnum;
import com.hanhai.zrb.model.user.User;
import com.hanhai.zrb.model.user.UserStatisticDetail;


@WebService(endpointInterface = "com.hanhai.zrb.api.client.facade.ResourceMatchFacade", serviceName = "ResourceMatchFacade")
@Service("resourceMatchFacade")
public class ResourceMatchFacadeImpl implements ResourceMatchFacade {
	
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Resource
	private FundService fundService;
	
	@Resource
	private SysDictionaryService sysDictionaryService;
	
	@Resource
	private IndustryService industryService;
	
	@Resource
	private CommonCounterService commonCounterService;
	@Resource
	private  ResourceMatchService resourceMatchService;
	@Resource
	private ProjectService projectService;
	@Resource
	private CityInfoService cityInfoService;

	@Override
	public List<Project> matchFundList(Integer type,Long bizid) {
         List<Project> list = new ArrayList<Project>();
         if(null!=bizid){
        	 
        	 ResourceMatchResult  resourceRet= resourceMatchService.recommend(type, bizid);
        	 List<ResourceMatchContent> retList = resourceRet.getResourceMatchContentList();
             if(CollectionUtils.isNotEmpty(retList)){
            	 List<Long> idsList = new ArrayList<Long>();
            	 for (ResourceMatchContent ret :retList ) {
            		 idsList.add(ret.getBizid());
				}
     			Map<Integer,Industry> industryMap =  industryService.selectAllMap();
    			List<SysDictionary> sysDicList = sysDictionaryService.listAll();
    			Map<String,SysDictionary> sysDicMap = new HashMap<String,SysDictionary>();
    			for(SysDictionary sysDic: sysDicList){
    				sysDicMap.put(sysDic.getItemCode(), sysDic);
    			}
    	         Map<Long,Project> map = projectService.queryMapByIdList(idsList);
                 list =buildProjectData(map, industryMap, sysDicMap); 
             }
        	 

         } 

         return list;
	}

	@Override
	public List<Project> matchIntentionFundList(Integer type,Long bizid) {
         List<Project> list = new ArrayList<Project>();
         if(null!=bizid){
        	 
        	 ResourceMatchResult  resourceRet= resourceMatchService.recommend(type, bizid);
        	 List<ResourceMatchContent> retList = resourceRet.getResourceMatchContentList();
             if(CollectionUtils.isNotEmpty(retList)){
            	 List<Long> idsList = new ArrayList<Long>();
            	 for (ResourceMatchContent ret :retList ) {
            		 idsList.add(ret.getBizid());
				}
     			Map<Integer,Industry> industryMap =  industryService.selectAllMap();
    			List<SysDictionary> sysDicList = sysDictionaryService.listAll();
    			Map<String,SysDictionary> sysDicMap = new HashMap<String,SysDictionary>();
    			for(SysDictionary sysDic: sysDicList){
    				sysDicMap.put(sysDic.getItemCode(), sysDic);
    			}
    	         Map<Long,Project> map = projectService.queryMapByIdList(idsList);
                 list =buildProjectData(map, industryMap, sysDicMap); 
             }
        	 

         } 

         return list;
	}
	
	
	public  List<Project> buildProjectData(Map<Long,Project> map,Map<Integer,Industry> industryMap,Map<String,SysDictionary> sysDicMap){
   	 List<Project> proLs = new ArrayList<Project>();
   	 for (Map.Entry<Long, Project> entry : map.entrySet()) {  
   		  proLs.add(entry.getValue());
        }
		if (null != proLs && proLs.size() > 0) {
			for (Project project : proLs) {
				String picName = project.getPic();
				if (StringUtils.isNotBlank(picName)) {
					int index = picName.lastIndexOf(".");
					if (index > 0) {
						String smallPicName = picName.substring(0, index)
								+ "_160x120" + picName.substring(index);
						project.setPic(smallPicName);
					}
				}
				if (null != project.getIndustryId()) {
					Industry industry = industryMap.get(project.getIndustryId());		
					if (null != industry) {
						project.setIndustryStr(industry.getIndustryName());
						project.setIndustryColor(industry.getColor());
					}
				}

				if (null != project.getProjectStatus()) {
					SysDictionary sysDictionary = sysDicMap.get(String.valueOf(project.getProjectStatus()));
					if (null != sysDictionary) {
						project.setProjectStatusStr(sysDictionary.getItemName());
					}
				}

				if (null != project.getMode()) {
					SysDictionary sysDictionary = sysDicMap.get(String.valueOf(project.getMode()));
					if (null != sysDictionary) {
						project.setModeStr(sysDictionary.getItemName());
					}
				}

				if (null != project.getAuth()) {
					SysDictionary sysDictionary = sysDicMap.get(String.valueOf(project.getAuth()));
					if (null != sysDictionary) {
						project.setAuthStr(sysDictionary.getItemName());
					}
				}
			}
		}
		return proLs;
	}
	
	@Override
	public List<AppFundVo> matchProjectList(Integer type,Long bizid) {
         List<FundSearchVo> list = new ArrayList<FundSearchVo>();
         List<Fund> fundList = new ArrayList<Fund>();
         if(null!=bizid){
        	 ResourceMatchResult  resourceRet= resourceMatchService.recommend(type, bizid);
        	 List<ResourceMatchContent> retList = resourceRet.getResourceMatchContentList();
        	 List<Long> idsList = new ArrayList<Long>();
        	 if(CollectionUtils.isNotEmpty(retList)){
        	 for (ResourceMatchContent ret :retList ) {
        		 idsList.add(ret.getBizid());
			}
        	 Map<Long,Fund> map = fundService.queryByIdList(idsList);
        	 
        	 for (Map.Entry<Long,Fund> entry:map.entrySet()) {
        		 fundList.add(entry.getValue());
			}
    		 
    	 }
        } 

         return buildAppFundVo(fundList);
	}
	
	@Override
	public List<AppFundVo> matchIntentionProjectList(Integer type,Long bizid) {
         List<FundSearchVo> list = new ArrayList<FundSearchVo>();
         List<Fund> fundList = new ArrayList<Fund>();
         if(null!=bizid){
        	 ResourceMatchResult  resourceRet= resourceMatchService.recommend(type, bizid);
        	 List<ResourceMatchContent> retList = resourceRet.getResourceMatchContentList();
        	 List<Long> idsList = new ArrayList<Long>();
        	 if(CollectionUtils.isNotEmpty(retList)){
        	 for (ResourceMatchContent ret :retList ) {
        		 idsList.add(ret.getBizid());
			}
        	 Map<Long,Fund> map = fundService.queryByIdList(idsList);
        	 
        	 for (Map.Entry<Long,Fund> entry:map.entrySet()) {
        		 fundList.add(entry.getValue());
			}
    		 
    	 }
        } 

         return buildAppFundVo(fundList);
	}
	
	private List<AppFundVo> buildAppFundVo(List<Fund> fundList){
		List<AppFundVo> voList = new ArrayList<AppFundVo>();
		try {
		if(CollectionUtils.isNotEmpty(fundList)){
			SysDictionary sys = new SysDictionary();
			Map<String,SysDictionary> map = sysDictionaryService.getItemsMap(sys);
			Map<Integer,Industry> industryMap = industryService.selectAllMap();
			
			List<String> idList = new ArrayList<String>();
			for (int i = 0; i < fundList.size(); i++) {
				if(null!=fundList.get(i).getId()){
					idList.add(String.valueOf(fundList.get(i).getId()));
				}
				
			}
			
			Map<String,Long> countMap = commonCounterService.listCountMapBySecondaryKeyList(UserStatisticDetail.Type.fund_col.getCountKey(), idList);
			
			
			for(Fund fund:fundList){
				AppFundVo vo = new AppFundVo();
				vo.setPic(fund.getPic());
				vo.setId(fund.getId());
				vo.setTitle(fund.getTitlesVal());				
				vo.setTotal(fund.getTotal());
				vo.setPushTime(fund.getPushTime());
				if(StringUtils.isNoneBlank(fund.getDestination())){
					String[] destIds = fund.getDestination().split("#");
					String areas = "";
					for(String id:destIds){
						if(!"".equals(areas)){
							areas=areas+"/"+ProvinceEnum.getProvinceName(Integer.valueOf(id));
						}else{
							areas=ProvinceEnum.getProvinceName(Integer.valueOf(id));
						}
					}
					vo.setAreas(areas);
				}
				
				if(null!=fund.getPushTime()){
					vo.setPeriod(DateUtil.getExactQuot(DateUtil.dateToStringFullFormat(new Date()), DateUtil.dateToStringFullFormat(fund.getPushTime())));
				}
				
				if(null!=fund.getAuth()&&null!=map.get(fund.getAuth().toString())){
					vo.setAuthName(map.get(fund.getAuth().toString().trim()).getItemName());
				}
				
				if(StringUtils.isNoneBlank(fund.getIndustryId())){
					String[] ids = fund.getIndustryId().split("#");
					String industryName ="";
					for(String industryId:ids){
						if(!"".equals(industryName)){
							industryName=industryName+"/"+industryMap.get(Integer.valueOf(industryId)).getIndustryName();
						}else{
							industryName=industryMap.get(Integer.valueOf(industryId)).getIndustryName();
						}
					}
					vo.setIndustryName(industryName);
				}
				if(null!=fund.getInvestMode() && null!=map.get(fund.getInvestMode().toString())){
					vo.setInvestMode(map.get(fund.getInvestMode().toString()).getItemName());
				}
				
				Long tempCount = countMap.get(String.valueOf(fund.getId()));
				if(tempCount == null){
					tempCount = 0L;
				}
				vo.setCollectNum(tempCount);
				voList.add(vo);
			}
		}
		} catch (ParseException e) {
			logger.error("get fund list from app failed because parse error");
		}
		return voList;
	}
	
	

	
	
}
